package com.shop.common.util;

import com.shop.common.entity.user.UserBase;
import com.shop.common.util.excption.UserNotFoundException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

public class SessionUtils {
    @Autowired
    private RedisUtil redisUtil;

    public UserBase GET_USER(HttpServletRequest request) throws UserNotFoundException {
        UserBase userBase = new UserBase();
        String token = request.getHeader("AUTHTOKEN");
        if (StringUtils.isBlank(token)) {
            throw new UserNotFoundException();
        }
        if (!redisUtil.exists(token)) {
            throw new UserNotFoundException();
        }
        userBase = (UserBase) redisUtil.getObject(token);
        if(userBase==null){
            throw new UserNotFoundException();
        }
        return userBase;
    }

    public Integer USER_ID(HttpServletRequest request) throws UserNotFoundException {
        UserBase userBase=GET_USER(request);
        return userBase==null?null:userBase.getUserId();
    }

    public void SET_USER(UserBase userBase, String token) {
        redisUtil.set(token, userBase,60*60*24*7);
    }

    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public void QUIT(HttpServletRequest request){
        UserBase userBase = new UserBase();
        String token = request.getHeader("AUTHTOKEN");
        if (StringUtils.isBlank(token)) {
            return;
        }
        if (!redisUtil.exists(token)) {
           return;
        }
        redisUtil.del(token);
    }
}
